/**
 * 
 */
package info.niwota.web.apache;

import info.niwota.commons.acl.AccessControl;
import info.niwota.web.ApplicationContext;
import info.niwota.web.Debug;
import info.niwota.web.Preferences;
import info.niwota.web.ServerApplication;
import info.niwota.web.Session;
import info.niwota.web.SiteConstants;
import info.niwota.web.peer.PeerHttpClient;

import java.net.URI;

import jvs.peer.io.ChannelManager;

import org.json.JSONObject;

import x.org.apache.http.HttpRequest;
import x.org.apache.http.HttpResponse;
import x.org.apache.http.protocol.HttpContext;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class HomeHandler extends BaseHandler {
	private static final String TAG = "HomeHandler";

	private static final String MAIN_TPL = "main.tpl";
	
	public HomeHandler(Context ctx) {
		super(ctx);
	}

	private static final ChannelManager manager = ApplicationContext.getChannelManager();
	
	@Override
	public boolean handle(String p, HttpRequest req, HttpResponse res, HttpContext context) {
		try {
			long startup = ServerApplication.startupTime;
			if (Debug.DEBUG) {
				Log.d(TAG, "handle path: " + p + " startupTime: " + startup);
			}
			p = (TextUtils.isEmpty(p) || p.equals("/") ? "/home" : p);
			
			boolean handle = p.startsWith("/home");
			if (handle) {
				
				Session s = getSession(context);
				
				boolean loggedIn = (s != null && s.authenticated);

				Object apps = null;
				Object peers = null;
				Object user = null;
				
				final Uri uri = Uri.parse("home://" + p.substring(5));
				
				//site access control
				boolean[] pa = Preferences.getAccess(ctx);

				if (!loggedIn) {
					//public access enabled?
					boolean publicOn = pa[AccessControl.ACCESS_PUBLIC];
					
					apps = publicOn ? ApplicationContext.getWebApps(ctx, AccessControl.ACCESS_PUBLIC) : null;
					user = ""; 

				} else {
					//logged-in user can only be: shared or master
					//furthermore , shared and master access must have been
					//enabled or user would not have been able to login
					//
					boolean sharedonly = Boolean.parseBoolean(uri.getQueryParameter("sharedonly"));
					apps = sharedonly ? ApplicationContext.getPeerApps(ctx, s.group) : ApplicationContext.getWebApps(ctx, s.group);
					boolean showPeer = (s.group == AccessControl.ACCESS_MASTER) || Preferences.isSharePeer(ctx);
					peers = showPeer ? ApplicationContext.getPeers(ctx) : null;
					user = s.user;
				}
				//
				final String peer = uri.getQueryParameter("peer");
				final String realm = uri.getQueryParameter("realm");

				String type = uri.getQueryParameter("type");
				String jid = manager.getJid();
				
				boolean islocal = (TextUtils.isEmpty(peer) || peer.equals(jid));
				
				type = (TextUtils.isEmpty(type) ? "html" : type);
				
				JSONObject json = null;
					
				if (islocal) {
					json = Preferences.getSiteInfo(ctx); // name, message, avatar
					
					json.put(SiteConstants.APPS, apps);
					json.put(SiteConstants.PEERS, peers);
					json.put(SiteConstants.USER, user);
					
				} else {
					
					if (TextUtils.isEmpty(jid)) {
						throw new Exception("XMPP peer service not available");
					}
					
					//always get json
					URI u = new URI("/home?type=json&sharedonly=true");
					if (Debug.DEBUG) {
						Log.d(TAG, "getting " + u + " from: " + peer);
					}
					PeerHttpClient client = (realm == null ? jabclient : blueclient);
					
					String rs = client.get(peer, u);
					json = new JSONObject(rs);
					
				}
				
				jid = (jid == null ? "" : jid);
						
				json.put("site.id", peer == null ? jid : peer);
				json.put("authenticated", loggedIn);
				json.put("jid", jid);
				
				json.put("ip", manager.getIp());
				json.put("port", manager.getPort());
				
				if ("html".equals(type)) {
					sendAssetData(req, res, MAIN_TPL , json);
				} else if ("json".equals(type)) {
					//ignore callback if gae/xmpp
					String xmpp = uri.getQueryParameter("xmpp");
					String callback = (xmpp != null && xmpp.equals("true") ? null : uri.getQueryParameter("callback"));
					sendJSONData(req, res, context, callback, json);
				} else if ("script".equals(type)) {
					String var = uri.getQueryParameter("var");
					sendScript(req, res, var == null? "siteinfo" : var, json);
				} else {
					throw new Exception("Not supported " + type);
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
